<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    const ORDER_STATUS = [
        '未付款',
        '未发货',
        '已发货',
        '待评论',
        '退货中',
        '已完成',
        '订单失效',
        '已关闭',
        '退货完成',
    ];

	protected $guarded = [];

    public function user()
    {
    	return $this->belongsTo(User::class);
    }

    public function order_goods()
    {
    	return $this->hasMany(OrderGoods::class, 'order_id');
    }

    public function address() {
    	return $this->belongsTo(Address::class);
    }

    public static function boot()
    {
    	parent::boot();
    	static::creating(function($model) {
    		$model->order_number = date('Ymdhis').random_int(1001, 9999);
    		$model->address_info = $model->address->full_address??'';
    	});
    }

    public function goods()
    {
        return $this->order_goods()->with('goods')->get();
    }

    public function getOrderStatAttribute($v) {
        return self::ORDER_STATUS[$this->status];
    }

    public function getOrderActionAttribute() {
        if($this->status == 0) {
            return ['text' => '去付款', 'link' => ''];
        }
        // if($this->status == 1) {
        //     return '申请退款';
        // }
        if(in_array($this->status, [1,2,3])) {
            return ['text' => '退货', 'link' => ''];
        }

        return '';
    }

    public function scopeUnpaid($query) {
        return $query->where('status', 0);
    }
}
